package com.ynet.middleground.user.model;

import java.time.LocalDateTime;
import java.util.*;

import org.apache.commons.lang.StringUtils;
import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.ynet.core.common.PagerInfo;
import com.ynet.core.exception.BusinessException;
import com.ynet.core.log.IfpLogger;
import com.ynet.middleground.user.bean.*;
import com.ynet.middleground.user.common.ErrorMessageConstant;
import com.ynet.middleground.user.common.SystemConstant;
import com.ynet.middleground.user.dao.*;
import com.ynet.middleground.user.dto.InPortRoleDto;
import com.ynet.middleground.user.dto.OrganRoleRelationshipDto;
import com.ynet.middleground.user.entity.*;
import com.ynet.middleground.user.utils.GeneralService;

/**
 * @program: 2019-10-12_userCenter
 * @description: 角色管理事务层
 * @author: DaiGaoLe
 * @create: 2019-10-28 17:41
 **/
@Component
public class RoleManagementModel extends ServiceImpl<UserBaseInformationMapper, UserBaseInformation> {

    @Autowired
    InPortRoleMapper inPortRoleMapper;

    @Autowired
    private Mapper dozerBeanMapper;

    @Autowired
    OrganizationalRoleRelationMapper organizationalRoleRelationMapper;

    @Autowired
    EmployeeInformationMapper employeeInformationMapper;

    @Autowired
    GeneralService generalService;

    @Autowired
    CommUtilsMapper commUtilsMapper;

    @Autowired
    OrganizationalStructureMapper organizationalStructureMapper;

    @Autowired
    OrganizationManagementModel organizationManagementModel;

    // 上传多渠道的话，约定以“,”隔开，例：C01,C02；
    private static final String queryChannelSplitFlag = ",";

    /* 添加角色 begin */
    @Transactional(rollbackFor = Exception.class)
    public Integer addRoleInfo(AddRoleInfoReq requestObject) {
        // 声明变量 begin
        Integer operationUserId = requestObject.getOperationUserId();
        String roleName = requestObject.getRoleName();
        Integer formatId = requestObject.getFormatId();
        LambdaQueryWrapper<InPortRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(InPortRole::getRoleName, roleName);
        queryWrapper.eq(InPortRole::getChannel, requestObject.getChannel());
        if(formatId!=null){
            if(organizationManagementModel.checkFormatId(formatId,requestObject.getChannel())){
                queryWrapper.eq(InPortRole::getFormatId, formatId);
            }else{
                throw new BusinessException(ErrorMessageConstant.ECUC0067_MESSAGE, ErrorMessageConstant.ECUC0067_CODE);
            }
        }
        // 声明变量 end

        InPortRole temp = inPortRoleMapper.selectOne(queryWrapper);
        if (temp != null) {
            throw new BusinessException("角色名称：" + roleName + "已经存在", ErrorMessageConstant.ECUC0027_CODE);
        }

        InPortRole inPortRole = dozerBeanMapper.map(requestObject, InPortRole.class);
        // inPortRole.setRoleId(CommUtils.getRandomId());
        inPortRole.setGmtCreate(LocalDateTime.now());
        inPortRole.setCreateBy(operationUserId);
        inPortRole.setGmtModified(LocalDateTime.now());
        inPortRole.setModifiedBy(operationUserId);
        inPortRoleMapper.insert(inPortRole);
        return inPortRole.getRoleId();
    }
    /* 添加角色 end */

    /* 查询角色 begin */
    public List<InPortRoleDto> queryRoleInfo(QueryRoleInfoReq requestObject) {
        // 声明变量 begin
        List<InPortRoleDto> inPortRoleDtolist = Lists.newArrayList();
        List<InPortRole> records = null;
        PagerInfo pagerInfo = requestObject.getPagerInfo();
        Page<InPortRole> inPortRolePage = new Page<>(pagerInfo.getPageNum(), pagerInfo.getPageSize());
        Integer formatId = requestObject.getFormatId();
        // 声明变量 end
        QueryWrapper<InPortRole> queryWrapper = new QueryWrapper<>();

        if (requestObject.getRoleId() != null && requestObject.getRoleId() > 0) {
            queryWrapper.eq("role_id", requestObject.getRoleId());
        }

        if (StringUtils.isNotEmpty(requestObject.getRoleName())) {
            queryWrapper.like("role_name", requestObject.getRoleName());
        }
        // Update By Liwq On 2020-11-03 Start
        // 增加按多渠道查询，约定以“,”隔开，例：C01,C02；
        if (StringUtils.isNotEmpty(requestObject.getQueryChannel())) {
            List<String> queryChannelList = Arrays.asList(requestObject.getQueryChannel().split(queryChannelSplitFlag));
            queryWrapper.in("channel", queryChannelList);
        }
        // Update By Liwq On 2020-11-03 End
        //2022-09-15 syf 新增业态id条件
        if(formatId!=null){
            queryWrapper.eq("format_id",formatId);
        }
        IPage<InPortRole> page = inPortRoleMapper.selectPage(inPortRolePage, queryWrapper);
        records = page.getRecords();
        for (InPortRole obj : records) {
            InPortRoleDto inPortRoleDto = new InPortRoleDto();

            dozerBeanMapper.map(obj, inPortRoleDto);
            inPortRoleDtolist.add(inPortRoleDto);
        }
        pagerInfo.setTotal(page.getTotal());
        return inPortRoleDtolist;
    }
    /* 查询角色 end */

    /* 修改角色 begin */
    @Transactional(rollbackFor = Exception.class)
    public String changeRole(ChangeRoleReq requestObject) {
        // 声明变量 begin
        Integer roleId = requestObject.getRoleId();
        Integer formatId = requestObject.getFormatId();
        QueryWrapper<InPortRole> queryWrapper = new QueryWrapper<>();
        String result = SystemConstant.SYSTEM_SUCCESS;
        // 声明变量 end
        queryWrapper.eq("role_id", roleId);
        InPortRole inPortRole = inPortRoleMapper.selectOne(queryWrapper);
        if (inPortRole == null) {
            throw new BusinessException("角色id：" + roleId + "不存在", ErrorMessageConstant.ECUC0027_CODE);
        }
        // 2022-09-16 syf增加业态判断
        if(formatId!=null){
            if(!formatId.equals(inPortRole.getFormatId())&&!requestObject.getChannel().equals(inPortRole.getChannel())){
                throw new BusinessException("渠道与业态不正确，请检查", ErrorMessageConstant.ECUC0055_CODE);
            }else if(!formatId.equals(inPortRole.getFormatId())){
                throw new BusinessException("业态不正确，请检查", ErrorMessageConstant.ECUC0055_CODE);
            }else if(!requestObject.getChannel().equals(inPortRole.getChannel())){
                throw new BusinessException("渠道不正确，请检查", ErrorMessageConstant.ECUC0055_CODE);
            }
        }else{
            if(!requestObject.getChannel().equals(inPortRole.getChannel())){
                throw new BusinessException("渠道不正确，请检查", ErrorMessageConstant.ECUC0055_CODE);
            }
        }
        QueryWrapper<OrganizationalRoleRelation> queryWrapperOrr = new QueryWrapper<>();
        queryWrapperOrr.eq("role_id", roleId);
        List<OrganizationalRoleRelation> organizationalRoleRelations =
            organizationalRoleRelationMapper.selectList(queryWrapperOrr);
        if (organizationalRoleRelations.size() > 0) {
            LambdaQueryWrapper<InPortRole> queryWrapperCN = new LambdaQueryWrapper<>();
            queryWrapperCN.eq(InPortRole::getRoleId, requestObject.getRoleId());
            queryWrapperCN.eq(InPortRole::getChannel, inPortRole.getChannel());
            InPortRole inPortRoleRN = inPortRoleMapper.selectOne(queryWrapperCN);
            throw new BusinessException("角色:" + inPortRoleRN.getRoleName() + ",角色id:" + roleId + "存在机构部门关联，不能修改",
                ErrorMessageConstant.ECUC0027_CODE);
        }
        if(StringUtils.isNotBlank(requestObject.getRoleName())) {
            LambdaQueryWrapper<InPortRole> queryWrapperCN = new LambdaQueryWrapper<>();
            queryWrapperCN.eq(InPortRole::getRoleName, requestObject.getRoleName());
            queryWrapperCN.eq(InPortRole::getChannel, inPortRole.getChannel());
            queryWrapperCN.eq(InPortRole::getFormatId, formatId);
            if(inPortRoleMapper.selectCount(queryWrapperCN)>0) {
                InPortRole inPortRoleRN = inPortRoleMapper.selectList(queryWrapperCN).get(0);
                if (inPortRoleRN != null && !roleId.equals(inPortRoleRN.getRoleId())) {
                    throw new BusinessException("角色名称:" + requestObject.getRoleName() + "已经存在",
                            ErrorMessageConstant.ECUC0027_CODE);
                }
            }
        }
        // 因为dozerBeanMapper.map会覆盖原来的渠道信息，所以需要临时保存一下。
        String tempChannel = inPortRole.getChannel();
        dozerBeanMapper.map(requestObject, inPortRole);
        inPortRole.setChannel(tempChannel);
        inPortRole.setModifiedBy(requestObject.getOperationUserId());
        inPortRole.setGmtModified(LocalDateTime.now());
        inPortRoleMapper.updateById(inPortRole);
        return result;
    }
    /* 修改角色 end */

    /* 删除角色 begin */
    @Transactional(rollbackFor = Exception.class)
    public String deleteRole(ChangeRoleReq requestObject) {
        // 声明变量 begin
        Integer roleId = requestObject.getRoleId();
        Integer formatId = requestObject.getFormatId();
        QueryWrapper<InPortRole> queryWrapper = new QueryWrapper<>();
        String result = SystemConstant.SYSTEM_SUCCESS;
        // 声明变量 end
        queryWrapper.eq("role_id", roleId);
        InPortRole inPortRole = inPortRoleMapper.selectOne(queryWrapper);
        if (inPortRole == null) {
            throw new BusinessException("角色id：" + roleId + "不存在", ErrorMessageConstant.ECUC0027_CODE);
        }
        // 2022-09-16 syf增加业态判断
        if(inPortRole.getFormatId()!=null) {
            if (!inPortRole.getFormatId().equals(formatId) && !requestObject.getChannel().equals(inPortRole.getChannel())) {
                throw new BusinessException("渠道与业态不正确，请检查", ErrorMessageConstant.ECUC0055_CODE);
            } else if (!inPortRole.getFormatId().equals(formatId)) {
                throw new BusinessException("业态不正确，请检查", ErrorMessageConstant.ECUC0055_CODE);
            }
        }else if(formatId!=null){
            if (!formatId.equals(inPortRole.getFormatId()) && !requestObject.getChannel().equals(inPortRole.getChannel())) {
                throw new BusinessException("渠道与业态不正确，请检查", ErrorMessageConstant.ECUC0055_CODE);
            } else if (!formatId.equals(inPortRole.getFormatId())) {
                throw new BusinessException("业态不正确，请检查", ErrorMessageConstant.ECUC0055_CODE);
            }
        }
        if (!requestObject.getChannel().equals(inPortRole.getChannel())) {
            throw new BusinessException("渠道不正确，请检查", ErrorMessageConstant.ECUC0055_CODE);
        }
        QueryWrapper<OrganizationalRoleRelation> queryWrapperOrr = new QueryWrapper<>();
        queryWrapperOrr.eq("role_id", roleId);
        List<OrganizationalRoleRelation> organizationalRoleRelations =
            organizationalRoleRelationMapper.selectList(queryWrapperOrr);
        if (organizationalRoleRelations.size() > 0) {
            LambdaQueryWrapper<InPortRole> queryWrapperCN = new LambdaQueryWrapper<>();
            queryWrapperCN.eq(InPortRole::getRoleId, requestObject.getRoleId());
            queryWrapperCN.eq(InPortRole::getChannel, inPortRole.getChannel());
            InPortRole inPortRoleRN = inPortRoleMapper.selectOne(queryWrapperCN);
            throw new BusinessException("角色:" + inPortRoleRN.getRoleName() + ",角色id:" + roleId + "存在机构部门关联，不能删除",
                ErrorMessageConstant.ECUC0027_CODE);
        }
        inPortRoleMapper.deleteById(inPortRole.getRoleId());
        return result;
    }
    /* 删除角色 end */

    /* 员工机构、部门、角色关系维护 begin */
    @Transactional(rollbackFor = Exception.class)
    public String addOrganRoleRelationship(AddOrganRoleRelationshipReq requestObject) {
        // 声明变量 begin
        Integer roleId = requestObject.getRoleId();
        String operationType = requestObject.getOperationType();
        Integer userId = requestObject.getUserId();
        Integer organizationalId = requestObject.getOrganizationalId();
        Integer operationUserId = requestObject.getOperationUserId();
        String channel = requestObject.getChannel();
        EmployeeInformation employeeInformation = null;
        Integer existCounts = 0;
        String result = SystemConstant.SYSTEM_SUCCESS;
        // 声明变量 end

        // Step1：校验 上传的用户、角色、机构/部门 是否都是正确的。
        Map<String, Integer> map = new HashMap<>();
        map.put("roleId", roleId);
        map.put("userId", userId);
        map.put("organizationalId", organizationalId);
        String exist = commUtilsMapper.isExist(map);
        if (StringUtils.isEmpty(exist)) {
            throw new BusinessException(ErrorMessageConstant.ECUC0055_MESSAGE, ErrorMessageConstant.ECUC0055_CODE);
        }

        // Step2: 校验 根据channel + 角色 + 用户 + 机构/部门 判断是否已经存在。
        LambdaQueryWrapper<OrganizationalRoleRelation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrganizationalRoleRelation::getChannel, channel);
        queryWrapper.eq(OrganizationalRoleRelation::getRoleId, roleId);
        queryWrapper.eq(OrganizationalRoleRelation::getUserId, userId);
        queryWrapper.eq(OrganizationalRoleRelation::getOrganizationalId, organizationalId);
        OrganizationalRoleRelation temp = organizationalRoleRelationMapper.selectOne(queryWrapper);

        // 添加场景校验 组合场景是否存在，添加的话，正常应该不存在，存在则报错
        if (SystemConstant.ORGAN_ROLE_RELATIONSHIP_TYPE_0.equals(operationType)) {
            if (temp != null) {
                throw new BusinessException(ErrorMessageConstant.ECUC0027_MESSAGE, ErrorMessageConstant.ECUC0027_CODE);
            }
        }
        // 删除场景校验 组合场景是否存在，删除的话，正常应该存在，不存在则报错
        if (SystemConstant.ORGAN_ROLE_RELATIONSHIP_TYPE_1.equals(operationType)) {
            if (temp == null) {
                throw new BusinessException(ErrorMessageConstant.ECUC0054_MESSAGE, ErrorMessageConstant.ECUC0054_CODE);
            }
        }

        // Step3：开始维护关系。
        // Step3.1: 添加场景
        // 添加操作涉及两张表，一张是ur_organizational_role_relation表，一张是ur_employee_information
        if (SystemConstant.ORGAN_ROLE_RELATIONSHIP_TYPE_0.equals(operationType)) {
            // Step3.1.1 首先操作ur_organizational_role_relation表，新增；
            OrganizationalRoleRelation organizationalRoleRelation =
                dozerBeanMapper.map(requestObject, OrganizationalRoleRelation.class);
            organizationalRoleRelation.setGmtCreate(LocalDateTime.now());
            organizationalRoleRelation.setCreateBy(operationUserId);
            organizationalRoleRelation.setGmtModified(LocalDateTime.now());
            organizationalRoleRelation.setModifiedBy(operationUserId);
            organizationalRoleRelationMapper.insert(organizationalRoleRelation);
            // Step3.1.2 再操作ur_employee_information表。
            // 要判断userid + channel + organizationalId + isDelete是否存在
            LambdaQueryWrapper<EmployeeInformation> lambdaQueryWrapper = new LambdaQueryWrapper<EmployeeInformation>();
            lambdaQueryWrapper.eq(EmployeeInformation::getIsDelete, SystemConstant.DELETE_FLAG_0);
            lambdaQueryWrapper.eq(EmployeeInformation::getUserId, userId);
            lambdaQueryWrapper.eq(EmployeeInformation::getChannel, channel);
            lambdaQueryWrapper.eq(EmployeeInformation::getOrganizationalId, organizationalId);
            existCounts = employeeInformationMapper.selectCount(lambdaQueryWrapper);

            // 找不到的话，说明没有在ur_employee_information维护组织关系，进行维护
            if (0 == existCounts) {
                // 新增EmployeeInformation企业员工数据时候，组织ID是空的，我们只需要把组织ID维护上就行
                // 根据isDelete + userid + channel + organizationalId is null
                // 找到原先“港内员工数据添加”接口新增的那条数据，进行修改。
                LambdaQueryWrapper<EmployeeInformation> query = new LambdaQueryWrapper<EmployeeInformation>();
                query.eq(EmployeeInformation::getIsDelete, SystemConstant.DELETE_FLAG_0);
                query.eq(EmployeeInformation::getUserId, userId);
                query.eq(EmployeeInformation::getChannel, channel);
                query.isNull(EmployeeInformation::getOrganizationalId);
                query.orderByDesc(EmployeeInformation::getGmtCreate);
                List<EmployeeInformation> employeeInformations = employeeInformationMapper.selectList(query);

                // Step3.1.2.1
                // 找到“港内员工数据添加”接口添加的那条数据了，进行修改；
                if (employeeInformations.size() != 0) {
                    employeeInformation = employeeInformations.get(0);
                    employeeInformation.setOrganizationalId(organizationalId);
                    employeeInformation.setGmtModified(LocalDateTime.now());
                    employeeInformation.setModifiedBy(operationUserId);
                    employeeInformationMapper.updateById(employeeInformation);
                }

                // Step3.1.2.2
                // 找不到数据，说明那条数据已经维护了 组织信息了，并且这个港内员工在多个组织下，
                // 我们复制一条数据过来，并把本次的组织ID维护进去。
                if (employeeInformations.size() == 0) {
                    LambdaQueryWrapper<EmployeeInformation> querys = new LambdaQueryWrapper<EmployeeInformation>();
                    querys.eq(EmployeeInformation::getIsDelete, SystemConstant.DELETE_FLAG_0);
                    querys.eq(EmployeeInformation::getUserId, userId);
                    querys.orderByDesc(EmployeeInformation::getGmtCreate);
                    List<EmployeeInformation> employees = employeeInformationMapper.selectList(querys);

                    if (employees.size() > 0) {
                        employeeInformation = employees.get(0);
                        employeeInformation.setChannel(channel);
                        employeeInformation.setOrganizationalId(organizationalId);
                        employeeInformation.setGmtCreate(LocalDateTime.now());
                        employeeInformation.setCreateBy(operationUserId);
                        employeeInformation.setGmtModified(LocalDateTime.now());
                        employeeInformation.setModifiedBy(operationUserId);
                        employeeInformationMapper.insert(employeeInformation);
                    }
                    // 如果根据userID + isDelete = 0，找不到数据的话，说明这个用户已经被删除了
                    // 给提示：请先添加港内员工数据，再维护关系
                    // 注：其实前面的代码已经有校验了，没数据会报错：请录入正确的用户，角色，机构/部门的id，
                    // 我们在这里再写一下保证万无一失
                    if (0 == employees.size()) {
                        throw new BusinessException(ErrorMessageConstant.ECUC0056_MESSAGE,
                            ErrorMessageConstant.ECUC0056_CODE);
                    }
                }
            }
        }
        // Step3.1: 删除场景
        if (SystemConstant.ORGAN_ROLE_RELATIONSHIP_TYPE_1.equals(operationType)) {
            // 需要调用审批中心获取用户是否存在（已经开启）任务不能删除
//            boolean joinUnfinishedProcess = generalService.isJoinUnfinishedProcess(userId, requestObject);
//            if (joinUnfinishedProcess) {
//                throw new BusinessException(ErrorMessageConstant.ECUC0004_MESSAGE, ErrorMessageConstant.ECUC0004_CODE);
//            }
            // Step3.1.1: 删除ur_organizational_role_relation表
            organizationalRoleRelationMapper.deleteById(temp.getId());
            // Step3.1.2: 操作ur_employee_information表；
            // 要判断，这个员工是否还在该渠道该公司担任任何角色，若不再担任任何角色，就直接把这条数据删除；
            LambdaQueryWrapper<OrganizationalRoleRelation> organizational =
                new LambdaQueryWrapper<OrganizationalRoleRelation>();
            organizational.eq(OrganizationalRoleRelation::getOrganizationalId, organizationalId);
            organizational.eq(OrganizationalRoleRelation::getUserId, userId);
            organizational.eq(OrganizationalRoleRelation::getChannel, channel);
            List<OrganizationalRoleRelation> oList = organizationalRoleRelationMapper.selectList(organizational);
            if (0 == oList.size()) {
                // 这个员工，在该渠道该公司下不担任角色了，直接删除。
                LambdaQueryWrapper<EmployeeInformation> lambdaQueryWrapper =
                    new LambdaQueryWrapper<EmployeeInformation>();
                lambdaQueryWrapper.eq(EmployeeInformation::getIsDelete, SystemConstant.DELETE_FLAG_0);
                lambdaQueryWrapper.eq(EmployeeInformation::getUserId, userId);
                lambdaQueryWrapper.eq(EmployeeInformation::getChannel, channel);
                lambdaQueryWrapper.eq(EmployeeInformation::getOrganizationalId, organizationalId);
                employeeInformation = employeeInformationMapper.selectOne(lambdaQueryWrapper);
                if (employeeInformation != null) {
                    employeeInformation.setIsDelete(SystemConstant.IS_DELETE_1);
                    employeeInformation.setGmtModified(LocalDateTime.now());
                    employeeInformation.setModifiedBy(operationUserId);
                    employeeInformationMapper.updateById(employeeInformation);
                }
                // 看看主表是否需要更新删除标记；
                LambdaQueryWrapper<EmployeeInformation> queryWrapperEID = new LambdaQueryWrapper<EmployeeInformation>();
                queryWrapperEID.eq(EmployeeInformation::getUserId, userId);
                queryWrapperEID.eq(EmployeeInformation::getIsDelete, SystemConstant.IS_DELETE_0);
                Integer count = employeeInformationMapper.selectCount(queryWrapperEID);
                if (0 == count) {
                    QueryWrapper<UserBaseInformation> queryWrapperUbi = new QueryWrapper<>();
                    queryWrapperUbi.eq("user_id", userId);
                    UserBaseInformation baseInformation = this.getBaseMapper().selectOne(queryWrapperUbi);
                    if (baseInformation != null) {
                        baseInformation.setIsDelete(SystemConstant.IS_DELETE_1);
                        baseInformation.setGmtModified(LocalDateTime.now());
                        baseInformation.setModifiedBy(operationUserId);
                        this.updateById(baseInformation);
                    }
                }
            }
        }
        return result;
    }

    /* 员工机构、部门、角色关系维护 end */

    /* 员工机构、部门、角色关系查询 begin */
    public List<OrganRoleRelationshipDto> queryOrganRoleRelationshipReq(QueryOrganRoleRelationshipReq requestObject) {
        IfpLogger.info(Thread.currentThread().getStackTrace()[1].getMethodName(), "员工机构、部门、角色关系查询, 请求信息：{}",
            requestObject);
        // 声明变量 begin
        Integer organizationalId = requestObject.getOrganizationalId();
        Integer roleId = requestObject.getRoleId();
        Integer userId = requestObject.getUserId();
        PagerInfo pagerInfo = requestObject.getPagerInfo();
        Integer formatId = requestObject.getFormatId();
        // 声明变量 end

        // Step1： 封装查询条件
        QueryWrapper<OrganizationalRoleRelation> queryWrapper = new QueryWrapper<>();
        if (organizationalId != null && organizationalId > 0) {
            queryWrapper.eq("organizational_id", organizationalId);
        }
        if (roleId != null && roleId > 0) {
            queryWrapper.eq("role_id", roleId);
        }
        if (userId != null && userId > 0) {
            queryWrapper.eq("user_id", userId);
        }
        //2022-11-2新增业态idsyf
        if(formatId != null && formatId > 0){
            LinkedHashMap<Integer, String> subs = new LinkedHashMap<>();
            List<Integer> ids = new ArrayList<>();
            ids.add(requestObject.getFormatId());
            getSubOrganizationalId(ids, subs);
            List<Integer> idList = new ArrayList<>(subs.keySet());
            idList.add(formatId);
            queryWrapper.in("organizational_id", idList);
        }
        // Update By Liwq On 2020-11-03 Start
        // 增加按多渠道查询，约定以“,”隔开，例：C01,C02；
        if (StringUtils.isNotEmpty(requestObject.getQueryChannel())) {
            List<String> queryChannelList = Arrays.asList(requestObject.getQueryChannel().split(queryChannelSplitFlag));
            queryWrapper.in("channel", queryChannelList);
        }
        // Update By Liwq On 2020-11-03 End

        List<OrganRoleRelationshipDto> organRoleRelationshipDtoList = new ArrayList<>();
        List<OrganizationalRoleRelation> records = new ArrayList<>();

        Page<OrganizationalRoleRelation> organizationalRoleRelationPage =
            new Page<>(pagerInfo.getPageNum(), pagerInfo.getPageSize());

        // Step2： 开始查询
        IPage<OrganizationalRoleRelation> page =
            organizationalRoleRelationMapper.selectPage(organizationalRoleRelationPage, queryWrapper);
        records = page.getRecords();

        // Step3: 查出来后，开始整理
        records.forEach(ojb -> {
            // Step3.1: 查询角色名称，组织名称等字段
            OrganRoleRelationshipDto organRoleRelationshipDto = new OrganRoleRelationshipDto();
            LinkedHashMap<Integer, String> institutional = new LinkedHashMap<>();
            LinkedHashMap<Integer, String> institutionalSectorHierarchy = new LinkedHashMap<>();
            Map<String, String> names = commUtilsMapper.getNames(ojb.getId());
            // Step3.2: 找出本部门的层级结构
            List<Integer> integerList = new ArrayList<>();
            integerList.add(ojb.getOrganizationalId());
            getSubOrganizationalId(integerList, institutional);// 子级
            getLastOrganizationalId(ojb.getOrganizationalId(), institutional);// 本身一级以及父级\
            institutionalSectorHierarchy = sortMap(institutional);// 按key排序
            // Step3.3: 组装Response对象
            dozerBeanMapper.map(ojb, organRoleRelationshipDto);
            organRoleRelationshipDto.setRoleName(names != null ? names.get("roleName") : null);
            organRoleRelationshipDto.setOrganizationalName(names != null ? names.get("organizationalName") : null);
            organRoleRelationshipDto.setUserName(names != null ? names.get("userName") : null);
            organRoleRelationshipDto.setInstitutionalSectorHierarchy(institutionalSectorHierarchy);
            // 找到当前级别的上一级别ID
            OrganizationalStructure organizationalStructureTemp = null;
            Integer tempId = null;
            Integer parentId = null;
            tempId = ojb.getOrganizationalId();
            organizationalStructureTemp = organizationalStructureMapper.selectById(tempId);
            if (organizationalStructureTemp != null) {
                parentId = organizationalStructureTemp.getParentId();
            }
            organRoleRelationshipDto.setFirstOrganizational(parentId);
            //2022-11-2增加业态相关syf
            OrganizationalStructure organTemp = null;
            if(ojb.getOrganizationalId()!=null){
                organTemp = organizationalStructureMapper.selectById(ojb.getOrganizationalId());
            }
            if(organTemp!=null){
                organTemp = organizationManagementModel.selectFormatIdByOrganizational(organTemp);
            }
            if(organTemp!=null){
                organRoleRelationshipDto.setFormatId(organTemp.getOrganizationalId());
            }
            organRoleRelationshipDtoList.add(organRoleRelationshipDto);
        });
        pagerInfo.setTotal(page.getTotal());
        return organRoleRelationshipDtoList;
    }
    /* 员工机构、部门、角色关系查询 end */

    /* 员工机构、部门、角色关系查询没有分页信息 begin */
    public List<OrganRoleRelationshipDto> queryOrganRoleRelationshipReq(QueryOrganRoleRelationReq requestObject) {
        IfpLogger.info(Thread.currentThread().getStackTrace()[1].getMethodName(), "员工机构、部门、角色关系查询-无分页查询, 请求信息：{}",
            requestObject);
        // 声明变量 begin
        Integer organizationalId = requestObject.getOrganizationalId();
        Integer roleId = requestObject.getRoleId();
        Integer userId = requestObject.getUserId();
        Integer formatId = requestObject.getFormatId();

        // 声明变量 end

        // Update By Liwq On 2020-12-01 Start
        // Step1： 封装查询条件
        QueryWrapper<OrganizationalRoleRelation> queryWrapper = new QueryWrapper<>();
        if (organizationalId != null && organizationalId > 0) {
            queryWrapper.eq("organizational_id", organizationalId);
        }
        if (roleId != null && roleId > 0) {
            queryWrapper.eq("role_id", roleId);
        }
        if (userId != null && userId > 0) {
            queryWrapper.eq("user_id", userId);
        }
        //2022-11-2新增业态idsyf
        if(formatId != null && formatId > 0){
            LinkedHashMap<Integer, String> subs = new LinkedHashMap<>();
            List<Integer> ids = new ArrayList<>();
            ids.add(requestObject.getFormatId());
            getSubOrganizationalId(ids, subs);
            List<Integer> idList = new ArrayList<>(subs.keySet());
            idList.add(formatId);
            queryWrapper.in("organizational_id", idList);
        }

        // 增加按多渠道查询，约定以“,”隔开，例：C01,C02；
        if (StringUtils.isNotEmpty(requestObject.getQueryChannel())) {
            List<String> queryChannelList = Arrays.asList(requestObject.getQueryChannel().split(queryChannelSplitFlag));
            queryWrapper.in("channel", queryChannelList);
        }

        // Step2： 开始查询
        List<OrganRoleRelationshipDto> organRoleRelationshipDtoList = new ArrayList<>();
        List<OrganizationalRoleRelation> organizationalRoleRelations =
            organizationalRoleRelationMapper.selectList(queryWrapper);

        // 用于缓存
        Map<Integer, Map<String, String>> namesCache = new HashMap<>(16);
        Map<Integer, LinkedHashMap<Integer, String>> institutionalSectorHierarchyCache = new HashMap<>(16);
        Map<Integer, Integer> parentIdCache = new HashMap<>(16);

        // Step3: 查出来后，开始整理
        if (organizationalRoleRelations != null) {
            organizationalRoleRelations.forEach(ojb -> {
                // 初始化用到的变量
                OrganRoleRelationshipDto organRoleRelationshipDto = new OrganRoleRelationshipDto();
                LinkedHashMap<Integer, String> institutional = new LinkedHashMap<>();
                LinkedHashMap<Integer, String> institutionalSectorHierarchy = new LinkedHashMap<>();
                Map<String, String> names = new HashMap<String, String>(16);
                Integer parentId = null;

                // Step3.1: 查询角色名称，组织名称等字段
                if (namesCache.containsKey(ojb.getId())) {
                    names = namesCache.get(ojb.getId());
                } else {
                    names = commUtilsMapper.getNames(ojb.getId());
                    namesCache.put(ojb.getId(), names);
                }

                // Step3.2: 找出本部门的层级结构
                if (institutionalSectorHierarchyCache.containsKey(ojb.getOrganizationalId())) {
                    institutionalSectorHierarchy = institutionalSectorHierarchyCache.get(ojb.getOrganizationalId());
                } else {
                    List<Integer> integerList = new ArrayList<>();
                    integerList.add(ojb.getOrganizationalId());
                    getSubOrganizationalId(integerList, institutional);// 子级
                    getLastOrganizationalId(ojb.getOrganizationalId(), institutional);// 本身一级以及父级
                    institutionalSectorHierarchy = sortMap(institutional);// 按key排序
                    institutionalSectorHierarchyCache.put(ojb.getOrganizationalId(), institutionalSectorHierarchy);
                }

                // 找到当前级别的上一级别ID
                if (parentIdCache.containsKey(ojb.getOrganizationalId())) {
                    parentId = parentIdCache.get(ojb.getOrganizationalId());
                } else {
                    OrganizationalStructure organizationalStructureTemp = null;
                    Integer tempId = null;
                    tempId = ojb.getOrganizationalId();
                    organizationalStructureTemp = organizationalStructureMapper.selectById(tempId);
                    if (organizationalStructureTemp != null) {
                        parentId = organizationalStructureTemp.getParentId();
                        parentIdCache.put(ojb.getOrganizationalId(), parentId);
                    }
                }

                // Step3.3: 组装Response对象
                dozerBeanMapper.map(ojb, organRoleRelationshipDto);
                organRoleRelationshipDto.setRoleName(names != null ? names.get("roleName") : null);
                organRoleRelationshipDto.setOrganizationalName(names != null ? names.get("organizationalName") : null);
                organRoleRelationshipDto.setUserName(names != null ? names.get("userName") : null);
                organRoleRelationshipDto.setInstitutionalSectorHierarchy(institutionalSectorHierarchy);
                organRoleRelationshipDto.setFirstOrganizational(parentId);
                //2022-11-2增加业态相关syf
                OrganizationalStructure organTemp = null;
                if(ojb.getOrganizationalId()!=null){
                    organTemp = organizationalStructureMapper.selectById(ojb.getOrganizationalId());
                }
                if(organTemp!=null){
                    organTemp = organizationManagementModel.selectFormatIdByOrganizational(organTemp);
                }
                if(organTemp!=null){
                    organRoleRelationshipDto.setFormatId(organTemp.getOrganizationalId());
                }
                organRoleRelationshipDtoList.add(organRoleRelationshipDto);
            });
        }
        return organRoleRelationshipDtoList;
        // Update By Liwq On 2020-12-01 End
    }
    /* 员工机构、部门、角色关系查询没有分页信息 end */

    /**
     * 找出本层级结构，以及父级层级结构
     *
     * @param id
     * @param result
     */
    public void getLastOrganizationalId(Integer id, LinkedHashMap<Integer, String> result) {
        OrganizationalStructure organizationalStructure = organizationalStructureMapper.selectById(id);
        if (organizationalStructure == null) {
            return;
        }
        result.put(organizationalStructure.getOrganizationalId(), organizationalStructure.getOrganizationalName());
        if (organizationalStructure.getParentId() == 0) {
            return;
        }
        getLastOrganizationalId(organizationalStructure.getParentId(), result);
    }

    /**
     * 找出本层级结构的所有子级层级结构
     * 
     * @Author Liwq
     * @param ids 要查询的层级，设置成List是因为:有的层级有很多子级别，查询这些子级别的下级，需要传多个ID;
     * @param results
     */
    public void getSubOrganizationalId(List<Integer> ids, LinkedHashMap<Integer, String> results) {
        // 无数据，直接返回
        if (ids.size() == 0) {
            return;
        }
        List<Integer> tempIdList = new ArrayList<>();
        // Step1: 查出该层级结构的子级
        LambdaQueryWrapper<OrganizationalStructure> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(OrganizationalStructure::getParentId, ids);
        List<OrganizationalStructure> organizationalStructures = organizationalStructureMapper.selectList(queryWrapper);

        // Step2: 将查询结果组装到LinkedHashMap; 并将组织ID封装到List,供递归调用
        for (OrganizationalStructure o : organizationalStructures) {
            // Step2.1: 查询结果组装到LinkedHashMap
            results.put(o.getOrganizationalId(), o.getOrganizationalName());

            // Step2.2: 将组织ID封装到List,供递归调用
            tempIdList.add(o.getOrganizationalId());
        }
        // Step3: 递归调用
        getSubOrganizationalId(tempIdList, results);
    }

    /**
     * 将传进来的linkedHashMap按照Key排序
     * 
     * @param linkedHashMap
     * @return
     */
    public LinkedHashMap<Integer, String> sortMap(LinkedHashMap<Integer, String> linkedHashMap) {
        if (linkedHashMap == null) {
            return null;
        }
        List<Map.Entry<Integer, String>> infoIds = new ArrayList<Map.Entry<Integer, String>>(linkedHashMap.entrySet());
        // 排序
        Collections.sort(infoIds, new Comparator<Map.Entry<Integer, String>>() {
            public int compare(Map.Entry<Integer, String> o1, Map.Entry<Integer, String> o2) {
                Integer p1 = o1.getKey();
                Integer p2 = o2.getKey();;
                return Integer.valueOf(p2) - Integer.valueOf(p1);// 如果要升序， 改为return
                                                                 // Integer.valueOf(p1)-Integer.valueOf(p2);
            }
        });
        // 转换成新map输出
        LinkedHashMap<Integer, String> newMap = new LinkedHashMap<Integer, String>();
        for (Map.Entry<Integer, String> entity : infoIds) {
            newMap.put(entity.getKey(), entity.getValue());
        }
        return newMap;
    }

}
